<?php

namespace App\Api\Controllers\JiuJiang;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class BaseController{
    
     // 表单提交字符集编码
    public $postCharset = "UTF-8";

    private $fileCharset = "UTF-8";
    
    public $url = 'https://pay.jjccb.com/JyPay/pospJson/'; // 地址
    public $privateKey = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAITJhWslAfX7xhag5l3kdXd+3oXsRMQF1RrZfmJ2E+0W81UuJBEo02gOi6KgYRJlVEULuLpibOXQlLbBNhB9Yc1YOQ15/4ZlU2q34rJkiOcu96SiR7hg68mcbt7eKj+PeTYjNrUfRo4xIr++N1RgWU55RAcpj/xSiyA1WNDCJXR5AgMBAAECgYAUwXs9WDeKP6Si/NuFaaSC3S3jOR82lMLOw5hhw5sxwBihA+lXVU5WQY/KB8+klHoroL1rRN9IvOXB+0l8Il0bA2E22/Xv+mvZ3ia9KIOBrDIvxsDyo59QhFjMUuvOdfJQKCiH+cVQAec4d38UoI/iaTRyt+RBCy9xeOZFJ5byQQJBAPxw+v5RHD2D6KuDPZPJHzZCAWB4+FbK4wFMOdEuKMq0q7Em7dy5OlulYnvLZjtM5x0MQNH4VbAI1VVu7tk4ZhUCQQCGqLp89fz9O0I5I+WXDhiMJ8s3yx3jfqkjcv8fX9DAjM9bWnIiu3cKMDw0VqKu4b7/rrrwKJIoJQMxsCdWFLHVAkEAhHhpTgGUVzecZjyVmLLm/RsAC/cPIsSPAURV5s5ZO545ptnt4nEVDbipCJuBB0dg1F50uXqexKSuBooTLswozQJASMYDEul18f0Giw7lUz9g8M3Iu7xfyMR48BmD2xbTIFx466vzpuWdLbpnrvlrLgv+RvvNN2EVq/Bky4OhnpnMiQJBAMy2Wb0Bl0ae8btM5kwQ8LHykBRcVDu8Z4t/aTtbQXyH5eo5t6Mz+jk3XyB11mdofNDqUUTSYeSs6eE6as7KLIU=';

    /**
     * 执行
     * @param string $url   请求地址后缀
     * @param array $data   请求参数
     * @param string $privateKey    商户私钥
     * @param string $publicKey    联动公钥
     * @return array -1：系统错误 1：成功 2：验签失败
     */
    public function http_post($url,$getparams,$data,$private_key){
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        openssl_sign($getparams, $signature, $privateKey, OPENSSL_ALGO_MD5);
        $data['signType']='RSA';//
        $sign = base64_encode($signature); // 签名
        $data['sign']=$sign;
        $data = json_encode($data);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    
    function add_refund_orders($refund_no,$out_trade_no,$refund_amount){
        $order=DB::table('orders')->where('out_trade_no',$out_trade_no)->select('store_id','created_at')->first();
        $data=array('refund_no'=>$refund_no,'refund_amount'=>$refund_amount,'out_trade_no'=>$out_trade_no,'store_id'=>$order->store_id,'refund_time'=>date('Y-m-d H:i:s',time()),'created_at'=>$order->created_at);
        
        $refund_order=DB::table('all_refund_orders')->where('out_trade_no',$out_trade_no)->select('store_id','created_at')->first();
        if(empty($refund_order)){
            DB::table('all_refund_orders')->insert($data);
        }
    }
    
    /**
     * 执行
     * @param string $url   请求地址后缀
     * @param array $data   请求参数
     * @param string $privateKey    商户私钥
     * @param string $publicKey    联动公钥
     * @return array -1：系统错误 1：成功 2：验签失败
     */
    public function http_post1($url,$getparams,$data,$private_key){
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        openssl_sign($getparams, $signature, $privateKey, OPENSSL_ALGO_MD5);
        $data['signType']='RSA';//
        $sign = base64_encode($signature); // 签名
        $data['sign']=$sign;
        $data = json_encode($data);
//        file_put_contents('5465465.log',var_export($url,true)."\r\n",FILE_APPEND);
//        file_put_contents('5465465.log',var_export($data,true)."\r\n",FILE_APPEND);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($curl);
//        file_put_contents('5465465.log',var_export($response,true)."\r\n",FILE_APPEND);
        curl_close($curl);
        return $response;
    }
    
    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }
    
     /**
     * 校验$value是否非空
     * if not set ,return true;
     * if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }


    /**
     * 商户秘钥加签
     * @param string $data 之前生成好的需加密内容
     * @param string $key 私钥
     * @return mixed 请求加签
     */
    public function reqSign($data, $key)
    {
        //请求加签
        $sign = $this->rsaSign($data, $key);
        $data['signature'] = $sign;

        return $sign;
    }


    /**
     * RSA签名
     * @param $data 待签名数据
     * @param $private_key 私钥字符串
     * @return string
     */
    private function rsaSign($data, $private_key)
    {
        //001 拼接请求明文串
        $sortData = $this->sortReqFields($data);
//        Log::info('联动-拼接请求明文串');
//        Log::info($data);
//        Log::info($sortData);
        //002 读取请求加签使用私钥
        $res = $this->loadPriKey($private_key);
        if ($res) {
            //003 使用私钥进行加签
            openssl_sign($sortData, $sign, $res, OPENSSL_ALGO_SHA1);
            openssl_free_key($res);
        } else {
            exit("私钥格式有误");
        }

        //004 对签名进行编码
        $sign = base64_encode($sign);

        return $sign;
    }


    /**
     * 拼接需要签名的内容
     * @param array $data 需签名的字段内容
     * @return string
     */
    private function sortReqFields($data)
    {
        unset($data['signature']);
        //递归解json嵌套操作
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $Parameters[$k] = $this->sortReqFields($v);
            } else {
                $Parameters[$k] = $v;
            }
        }

        //按字典序排序参数
        ksort($Parameters);

        $sign = '';

        foreach ($Parameters as $k => $v) {
            if ($v == null || $v == '') {
                continue;
            }
            //如果值非空则添加
            $sign .= $k . "=" . $v . "&";
        }

        $sign = rtrim($sign, '&');

        return $sign;
    }


    /**
     * 加载请求使用商户私钥
     * @param string $private_key
     * @return bool|resource
     */
    private function loadPriKey($private_key)
    {
        $private_key = chunk_split($private_key, 64, "\n");
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $private_key . "-----END RSA PRIVATE KEY-----\n";

        $res = openssl_get_privatekey($private_key);

        return $res;
    }


    private function sortRespFields($data)
    {
        foreach ($data as $k => $v) {
            if ($k == 'signature') {
                continue;
            }
            if (is_array($v)) {
                $Parameters[$k] = $this->sortRespFields($v);
            } else {
                $Parameters[$k] = $v;
            }
        }

        //按字典序排序参数
        ksort($Parameters);

        $sign = '';

        foreach ($Parameters as $k => $v) {
            if ($v == null || $v == '') {
                continue;
            }
//            $domain = strstr($v, '"');
//            if($domain != false){
//                $v = str_replace('"',"",$v);
//            }

            $sign .= $v . "|";
        }

        $sign = rtrim($sign, '|');

        return $sign;
    }


    /**
     * 获取响应验签使用联动公钥
     * @param string $pubCertKey 公钥
     * @return mixed
     */
    private function loadCert($pubCertKey)
    {
        $cert = chunk_split($pubCertKey, 64, "\n");
        $cert = "-----BEGIN CERTIFICATE-----\n" . $cert . "-----END CERTIFICATE-----\n";

        $res = openssl_pkey_get_public($cert);
        $detail = openssl_pkey_get_details($res);
        openssl_free_key($res);

        if (!$detail) {
            throw new Exception('loadX509Cert::openssl_pkey_get_details ERROR');
        }

        return $detail['key'];
    }


}
